import React, {Component} from 'react';
import {Dimensions, FlatList, Modal, StyleSheet, Text, TextInput, TouchableNativeFeedback, View} from 'react-native';
import ScrollableTabView, {DefaultTabBar} from 'react-native-scrollable-tab-view';
import Toast from './component/Toast';
import Loading from './component/Loading';
import HasReadScene from './costMaster/HasReadScene';
import axiosInstance from './utils/request';


//获取屏幕的宽度
const WIN_WIDTH = Dimensions.get('window').width;

export default class CostMasterScene extends Component {


    constructor(props){
		super(props);
		const { params } = this.props.route;
		this.props.navigation.setOptions({
			title: params.bookName,
		})
		this.state = {
			count:0,
			loading:true,
			animationType: 'none',//none slide fade
			modalVisible: false,//模态场景是否可见
			transparent: false,//是否透明显示
			tabIndex:0,
			bookId:params.bookId,
			bookName:params.bookName,
			months:global.user.accountCycle.months,
			currMonth:global.user.accountCycle.currMonth,
			custCode:'',
			custName:'',
			meterCode:'',
	 	};
	}

	setModalVisible = (visible) => {
    	let tabIndex=this.state.tabIndex;
		if(tabIndex==0){
			this.setState({ modalVisible: visible });
		}else if(tabIndex==1){
			this.refs.hasReadSceneRef.setModalVisible(true,'hasRead');
		}else if(tabIndex==2){
			this.refs.noReadSceneRef.setModalVisible(true,'');
		}
    }


	setHeader(tabIndex){
		this.setState(
		{
			tabIndex:tabIndex
		},()=>{

		})
	}

    //组件挂载完成后执行的方法
    componentDidMount(){
		this.props.navigation.setParams({ setModalVisible: this.setModalVisible });
        this.fetchData();
    }

    //下载数据
	fetchData() {
		const { params } = this.props.route;
		let bookId = params.bookId;
		let custCode=this.state.custCode;
		let custName=this.state.custName;
		let meterCode=this.state.meterCode;
		let currMonth=this.state.currMonth;
		let url=global.server.url+'/costMaster/selectList';
		axiosInstance.post(url,
			{
				bookId:bookId,
				custCode:custCode,
				custName:custName,
				meterCode:meterCode,
				currMonth:currMonth,
			}
		)
        .then(res => {
			let datas = [];
            datas = datas.concat(res.rows);
            this.setState({
				loading:false,
				datas:datas,
				count:datas.length
            });
        })
        .catch(err => {
        	this.setState({
			   	loading:false
			});
			 Toast.show("网络异常，请稍后再试！"+err);
        })
	}

	renderRow = (rowData) => {
		let bookId=this.state.bookId;
		let months=this.state.months;
		let currMonth=this.state.currMonth;
        return (
            <TouchableNativeFeedback
				onPress = {() => {
				this.props.navigation.navigate('Entry',
					{sno:rowData.sno,custCode:rowData.custCode,custName:rowData.custName,meterCode:rowData.meterCode,bookId:bookId,currMonth:currMonth,months:months})
				}}>
				<View style={styles.textMainStyle}>
					<Text style={styles.margin}>用户编号：{rowData.custCode}</Text>
					<Text style={styles.margin}>用户名称：{rowData.custName}</Text>
					<Text style={styles.margin}>用户地址：{rowData.address}</Text>
					<Text style={styles.margin}>水表编号：{rowData.meterCode}</Text>
					<Text style={styles.margin}>上期读数：{rowData.priorReading}</Text>
					<Text style={styles.margin}>本期读数：{rowData.currReading}</Text>
					<Text style={styles.margin}>实用度数：{rowData.quantity}</Text>
				</View>
			</TouchableNativeFeedback>
        )
    }

    render() {
        //加载后
        return (
			<ScrollableTabView
				style={styles.container}
				tabBarUnderlineStyle={{backgroundColor:'#000000', height:1}}
				renderTabBar={()=><DefaultTabBar backgroundColor='rgba(135, 206 ,235, 0.5)' />}
				tabBarPosition='bottom'
				onChangeTab={
                    (obj) => {
						this.setHeader(obj.i);
                    }
                }
		    >
				<View style={styles.container} tabLabel="全部">
					{
						this.state.loading==true?(<Loading/>):(null)
					}
						<View style={{
							height:30,
							flexDirection:'row',
							alignItems:'center',
							borderBottomWidth:1,
							borderBottomColor:'#D7D7D7',
							backgroundColor:"#F5FCFF",
							paddingLeft:6
						}}>
							<View style={styles.flex}>
								<Text style={{fontSize:16,fontWeight:"bold",textAlign:"left",marginTop:5}}>{this.state.currMonth}</Text>
							</View>
							<View style={styles.flex}>
								<Text style={{fontSize:16,fontWeight:"bold",textAlign:"left",marginTop:5}}>总记录数：{this.state.count}</Text>
							</View>
							<View style={styles.flex}>
								<TouchableNativeFeedback
									activeOpacity={0.5}
									onPress = {() => {
									  this.props.navigation.navigate('CustInfoOrderScene',{bookId:this.state.bookId,bookName:this.state.bookName})
									}}>
									<Text style={styles.headerText}>排序管理</Text>
								</TouchableNativeFeedback>
							</View>
					    </View>
						<FlatList
							tabLabel =''
							data = {this.state.datas}
							renderItem = {({item}) =>
								this.renderRow(item)
							}
							ListHeaderComponent={this._renderHeader(0)}
							//ListEmptyComponent={this.emptyComponent(1)}
						  />
					</View>
					<View style={styles.container} tabLabel ="已抄">
						<HasReadScene bookId={this.state.bookId} ref='hasReadSceneRef' currMonth={this.state.currMonth} memo={'hasRead'} navigation={this.props.navigation}/>
					</View>
					<View style={styles.container} tabLabel ="未抄">
						<HasReadScene bookId={this.state.bookId} ref='noReadSceneRef' currMonth={this.state.currMonth} memo={''} navigation={this.props.navigation}/>
					</View>
		     </ScrollableTabView>
        );
    }

	searchData(index){
		this.fetchData();
		this.setState({
			custCode:'',
			custName:'',
            meterCode:''
        });
		this.setModalVisible(false);
	}

	emptyComponent(index) {
		return (
            <View style={{
				backgroundColor: 'white', flex: 1, height: 500, alignItems: 'center',
				justifyContent: 'center',
			}}>
				<Text>抱歉，没有符合条件的记录，请核对查询条件！</Text>
			</View>
		)
	}

	//渲染头部
	 _renderHeader = (index) => {
         return(
            <View style={{alignItems:'center',flex:1}}>
				<Modal
					animationType={this.state.animationType}
					transparent={this.state.transparent}
					visible={this.state.modalVisible}
					onRequestClose={() => {
						this.setModalVisible(false)
					}}
				 >
				<View style={[styles.modalContainer,{backgroundColor: 'rgba(0, 0, 0, 0.5)'}]}>
					<View style={[styles.innerContainer,{backgroundColor: '#F0F8FF', padding: 20}]}>
						<View style={styles.row}>
							<View >
								<Text style={styles.tips}>请输入一个或多个条件</Text>
							</View>
							<TextInput
								style={styles.textInput}
								placeholder={'用户名称'}
								onChangeText={(text) => {
									this.custName = text;
									this.setState({custName: text})
								}}
								//输入框下划线
								underlineColorAndroid={'transparent'}/>
							<TextInput
								style={styles.textInput}
								placeholder={'用户编号'}
								onChangeText={(text) => {
									this.custCode = text;
									this.setState({custCode: text})
								}}
								//输入框下划线
								underlineColorAndroid={'transparent'}/>
							<TextInput
								style={styles.textInput}
								placeholder={'水表编号'}
								onChangeText={(text) => {
									this.meterCode = text;
									this.setState({meterCode: text})
							 }}
							 	//输入框下划线
								 underlineColorAndroid={'transparent'}/>
						</View>
						<View style={styles.settingStyle}>
							<Text
								onPress={this.searchData.bind(this,index)}
								style={{fontSize:20,marginTop:10}}>
								确定
							</Text>
							<Text
								onPress={this.setModalVisible.bind(this,false) }
								style={{fontSize:20,marginTop:10}}>
								关闭
							</Text>
						</View>
						</View>
					</View>
				</Modal>
      		</View>
        )
    }
}

var width = WIN_WIDTH/2;
const styles = StyleSheet.create({
    container: {
       flex: 1,
       flexDirection: 'column',
       backgroundColor: 'white'
    },
    headerView:{
		flex: 1,
		backgroundColor: 'skyblue',
		justifyContent : 'center',
		alignItems: 'center'
    },
    pagerView:{
		flex: 6,
		backgroundColor: 'white'
    },
    lineStyle: {
     // width:ScreenWidth/3,
		height: 2,
		backgroundColor: '#FF0000',
	},
	textMainStyle: {
		 flex: 1,
		 backgroundColor: 'white',
		 padding: 10,
		 paddingVertical:10,
		 marginLeft: 5,
		 marginRight: 5,
		 marginVertical: 3,
		 borderColor: '#dddddd',
		 borderStyle: null,
		 borderWidth: 0.5,
		 borderRadius: 2,
		 shadowColor: 'gray',    // 设置阴影
		 shadowOffset: {width:0.5, height: 0.5},
		 shadowOpacity: 0.4,   // 透明度
		 shadowRadius: 1,
		 elevation:2   //   高度，设置Z轴，可以产生立体效果
	},
	textHeaderStyle:{
		fontSize: 40,
		color: 'white',
	},
	headerText:{
		fontSize:16,
		fontWeight:"bold",
		textAlign:"right",
		marginTop:5,
		marginRight:10,
		height:25,
		backgroundColor:"#F5FCFF",
	},
	headerSeparator:{
		height:1,
		backgroundColor:"black",
	},
	modalContainer:{
		flex: 1,
		justifyContent: 'center',
		padding: 40,
	},
	innerContainer: {
		borderRadius: 10,
		alignItems: 'center',
	},
	tips:{
		textAlign: 'center',
		marginBottom: 5,
		fontSize: 20
	},
	textInput: {
		height: 40,
		width: width,
		marginBottom: 5,
		backgroundColor: 'white',
		textAlign: 'center',
		borderRadius:5
	},
	settingStyle:{
        flexDirection:'row',
        justifyContent:'space-between',
        width:width - 40,

	},
	flex:{
		flex:1
	},
	margin:{
	  fontWeight:"bold",
	}
});

